package com.icode.web.startup.oauth2;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by ZhongGang
 * at 2015/1/24
 */
@Configuration
@EnableOAuth2Client
public class ResourceConfig {

    @Resource
    @Qualifier("accessTokenRequest")
    private AccessTokenRequest accessTokenRequest;

    @Resource
    @Qualifier("oauth2ClientContext")
    private OAuth2ClientContext oauth2ClientContext;

    @Bean
    public OAuth2ProtectedResourceDetails store() {
        AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
        details.setId("store/order");
        details.setClientId("order");
        details.setClientSecret("secret");
        details.setUserAuthorizationUri("http://localhost:8080/store/oauth/authorize");
        details.setAccessTokenUri("http://localhost:8080/store/oauth/token");
        details.setScope(Arrays.asList("read", "write"));
        return details;
    }

    @Bean
    public OAuth2RestTemplate storeRestTemplate() {
        List<HttpMessageConverter<?>> converters = new ArrayList<>();
        converters.add(new FastJsonHttpMessageConverter());

        OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(store(), oauth2ClientContext);
        oAuth2RestTemplate.setMessageConverters(converters);
        return oAuth2RestTemplate;
    }
}
